package portal.web.servlets;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hornetq.utils.json.JSONArray;
import org.hornetq.utils.json.JSONException;
import org.hornetq.utils.json.JSONObject;

import portal.entidades.Configuracion;
import portal.web.delegate.IPortalWebDelegate;
import portal.web.delegate.PortalWebDelegate;
import portal.web.helpers.DataTableRequestParam;
import portal.web.helpers.DataTablesParamUtility;


@WebServlet("/Configuracion/ConfiguracionList")
public class ConfiguracionList extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public ConfiguracionList() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		IPortalWebDelegate app = PortalWebDelegate.getInstanace();

		final DataTableRequestParam param = DataTablesParamUtility
				.getParam(request);

		String sEcho = param.sEcho;
		int iTotalRecords; // total number of records (unfiltered)
		int iTotalDisplayRecords;// value will be set when code filters
									// companies by keyword
		JSONArray data = new JSONArray(); // data that will be shown in the
											// table

		List<Configuracion> configuraciones = app.listar();

		List<Configuracion> configsFiltered = new LinkedList<Configuracion>();

		iTotalRecords = configuraciones.size();

		for (Configuracion c : configuraciones) {
			// Cannot search by column 0 (id)
			if (param.bSearchable[1]
					&& c.getValor().toLowerCase()
							.contains(param.sSearchKeyword.toLowerCase())
					|| param.bSearchable[2]
					&& c.getNumeroGrupo().toString().toLowerCase()
							.contains(param.sSearchKeyword.toLowerCase())
					|| param.bSearchable[3]
					&& c.getTipoServicio().toLowerCase()
							.contains(param.sSearchKeyword.toLowerCase())) {
				configsFiltered.add(c); // Add a company that matches search
										// criterion
			}
		}
		iTotalDisplayRecords = configsFiltered.size();// Number of companies
														// that
		// matches search criterion
		// should be returned

		Collections.sort(configsFiltered, new Comparator<Configuracion>() {
			@Override
			public int compare(Configuracion c1, Configuracion c2) {
				int result = 0;
				for (int i = 0; i < param.iSortingCols; i++) {
					int sortBy = param.iSortCol[i];
					if (param.bSortable[sortBy]) {
						switch (sortBy) {
						case 0:
							result = 0; // sort by id is not allowed
							break;
						case 1:
							result = c1.getValor().toString()
									.compareToIgnoreCase(c2.getValor())
									* (param.sSortDir[i].equals("asc") ? -1 : 1);
							break;
						case 2:
							result = c1
									.getNumeroGrupo()
									.toString()
									.compareToIgnoreCase(
											c2.getNumeroGrupo().toString())
									* (param.sSortDir[i].equals("asc") ? -1 : 1);
							break;
						case 3:
							result = c1.getTipoServicio().compareToIgnoreCase(
									c2.getTipoServicio())
									* (param.sSortDir[i].equals("asc") ? -1 : 1);
							break;
						}
					}
					if (result != 0)
						return result;
					else
						continue;
				}
				return result;
			}

		});

		if (configsFiltered.size() < param.iDisplayStart + param.iDisplayLength)
			configsFiltered = configsFiltered.subList(param.iDisplayStart,
					configsFiltered.size());
		else
			configsFiltered = configsFiltered.subList(param.iDisplayStart,
					param.iDisplayStart + param.iDisplayLength);

		try {
			JSONObject jsonResponse = new JSONObject();

			jsonResponse.put("sEcho", sEcho);
			jsonResponse.put("iTotalRecords", iTotalRecords);
			jsonResponse.put("iTotalDisplayRecords", iTotalDisplayRecords);

			for (Configuracion c : configsFiltered) {
				JSONArray row = new JSONArray();
				row.put(c.getId()).put(c.getValor())
						.put(c.getNumeroGrupo().toString())
						.put(c.getTipoServicio());
				data.put(row);
			}
			jsonResponse.put("aaData", data);

			response.setContentType("application/json");
			response.getWriter().flush();
			response.getWriter().print(jsonResponse.toString());
		} catch (JSONException e) {
			e.printStackTrace();
			response.setContentType("text/html");
			response.getWriter().print(e.getMessage());
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
